package com.glsc.ngateway.flowable.listener.demandmanagement;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.flowable.dto.ParamEmailDto;
import com.glsc.ngateway.common.api.flowable.dto.demand.FlowableAppendDto;
import com.glsc.ngateway.common.api.flowable.dto.demand.FlowableDemandDto;
import com.glsc.ngateway.common.api.flowable.dto.demand.OnlineInf;
import com.glsc.ngateway.common.base.domain.mysql.flowable.FlowableAppend;
import com.glsc.ngateway.common.base.domain.mysql.flowable.FlowableDemand;
import com.glsc.ngateway.common.base.domain.mysql.flowable.FlowableEhrEmp;
import com.glsc.ngateway.common.base.repo.mysql.flowable.FlowableAppendRepo;
import com.glsc.ngateway.flowable.service.FlowableAppendService;
import com.glsc.ngateway.flowable.service.FlowableDemandService;
import com.glsc.ngateway.flowable.service.FlowableEhrEmpService;
import com.glsc.ngateway.flowable.service.MailService;
import org.apache.commons.lang.StringUtils;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class DemandManagementOnlineHandler implements TaskListener, ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(DemandManagementOnlineHandler.class);


    private static ApplicationContext applicationContext;

    @Autowired
    FlowableAppendRepo appendRepo;

    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        applicationContext = arg0;
    }


    @Override
    public void notify(DelegateTask delegateTask) {

        try {
            if (("ysp").equals(delegateTask.getTenantId())) {
                delegateTask.setVariable("isSkipCheck", "1");
            } else {
                delegateTask.setVariable("isSkipCheck", "0");
            }
            FlowableDemandService flowableDemandService = (FlowableDemandService) applicationContext.getBean("flowableDemandService");
            String content = delegateTask.getVariable("content").toString();
            JSONObject json = JSONObject.parseObject(content);
            String title = json.getString("title");
            JSONObject demandSubmit = json.getJSONObject("demandSubmit");
            FlowableDemand demand = JSON.parseObject(demandSubmit.toJSONString(), FlowableDemand.class);
            List<FlowableDemandDto> exist = flowableDemandService.findByProcessInstanceId(delegateTask.getProcessInstanceId());
            FlowableDemandDto demandExist = exist.get(0);
            if (demandExist != null) {
                List<OnlineInf> alist = JSONObject.parseArray(demand.getOnlineinfo(), OnlineInf.class);
                for (OnlineInf l : alist) {
                    FlowableEhrEmpService flowableEhrEmpService = (FlowableEhrEmpService) applicationContext.getBean("flowableEhrEmpService");
                    if (flowableEhrEmpService != null) {
                        l.setDevUserName(flowableEhrEmpService.getChineseName(l.getDevUserId()));
                    }
                }
                String online = JSONObject.toJSONString(alist);
                demandExist.setOnlineinfo(online);
                flowableDemandService.saveDemandSubmit(demandExist);
                //获取上线日期
                List<JSONObject> onlineArray = JSON.parseArray(demandExist.getOnlineinfo(),JSONObject.class);
                String onlineDate = onlineArray.get(0).getString("actualOnlineDate");
                //获取附件
                List<File> attachFiles = new ArrayList<>();
                if (StringUtils.isNotEmpty(demandExist.getDemandDocument())){
                    List<JSONObject> attachArray = JSON.parseArray(demandExist.getDemandDocument(),JSONObject.class);
                    if (CollectionUtil.isNotEmpty(attachArray)){
                        List<String> attachIds = attachArray.stream().map(e-> e.getString("annexId")).collect(Collectors.toList());
                        FlowableAppendService flowableAppendService = (FlowableAppendService) applicationContext.getBean("flowableAppendService");
                        List<FlowableAppendDto> appends = flowableAppendService.findByAppendixIdIn(attachIds);
                        if (CollectionUtil.isNotEmpty(appends)){
                            attachFiles = appends.stream().map( append ->  new File(append.getAppendixPath())).collect(Collectors.toList());
                        }
                    }
                }

                //发送邮件通知模块
                try {
                    logger.info("需求管理上线，发送通知邮件开始。需求人:" + demandExist.getStaff());
                    MailService mailService = (MailService) applicationContext.getBean("mailService");
                    FlowableEhrEmpService flowableEhrEmpService = (FlowableEhrEmpService) applicationContext.getBean("flowableEhrEmpService");
                    FlowableEhrEmp emp = flowableEhrEmpService.getUserInfo(demandExist.getStaff());
                    if (emp != null) {
                        ParamEmailDto dto = new ParamEmailDto();
                        dto.setContext(createHtmlContent(demandExist.getDemandDetail(), title));
                        dto.setTitle(title+"-上线日"+onlineDate+"-上线提醒");
                        if (CollectionUtil.isNotEmpty(attachFiles)){
                            dto.setAttachmentList(attachFiles);
                        }
                        dto.setRecipient(emp.getEmail());
                        mailService.sendEmail(dto);
                        logger.info("需求管理上线，发送通知邮件结束。收件email:" + emp.getEmail());
                    } else {
                        logger.info("需求管理上线，未发送通知邮件。未找到该用户邮箱。" + demandExist.getStaff());
                    }
                    //通知原始需求人
                    if (!StringUtils.isEmpty(demandExist.getOriginalStaff())) {
                        List<FlowableEhrEmp> emporg = flowableEhrEmpService.getUserListByName(demandExist.getOriginalStaff());
                        if (emporg != null && emporg.size() > 0) {
                            for (FlowableEhrEmp em : emporg) {
                                if (em.getTitle().contains("资产管理部") || em.getTitle().contains("股权衍生品业务部") || em.getTitle().contains("运营管理总部")) {
                                    logger.info("需求管理上线，发送通知邮件开始。原始需求人:" + demandExist.getOriginalStaff());
                                    ParamEmailDto dto = new ParamEmailDto();
                                    dto.setContext(createHtmlContent(demandExist.getDemandDetail(), title));
                                    dto.setTitle(title+"-上线日"+onlineDate+"-上线提醒");
                                    if (CollectionUtil.isNotEmpty(attachFiles)){
                                        dto.setAttachmentList(attachFiles);
                                    }
                                    dto.setRecipient(em.getEmail());
                                    mailService.sendEmail(dto);
                                    logger.info("需求管理上线，发送通知邮件结束。收件email:" + em.getEmail());
                                }
                            }
                        } else {
                            logger.info("需求管理上线，未发送通知邮件。未找到该用户邮箱。" + demandExist.getOriginalStaff());
                        }
                    }
                } catch (Exception e) {
                    logger.error("DemandManagementOnlineHandler发送邮件异常，主流程继续。processid=" + delegateTask.getProcessInstanceId(), e);
                }
            }
        } catch (Exception e) {
            logger.error("DemandManagementOnlineHandler处理异常，结束处理。processid=" + delegateTask.getProcessInstanceId(), e);
            throw new RuntimeException("DemandManagementOnlineHandler处理异常，结束处理。processid=" + delegateTask.getProcessInstanceId(), e);
        }
    }

    private String createHtmlContent(String demand, String title) {
        return "<html lang='en' style='margin: 0; padding: 0; font-family: Helvetica Neue, Microsoft Yahei, Hiragino Sans GB, WenQuanYi Micro Hei, sans-serif; font-size: 14px; text-align: center; word-break: normal; font-weight: normal;'>"
                + "<head>"
                + "<style type='text/css'>body {border-width:0;margin:0}img {border:0;margin:0;padding:0}</style><base target='_blank' />"
                + "</head>"
                + "<p>您好：</p>"
                + "<p>     您所提交的需求已经完成上线，请确认。    </p>"
                + "<p>     需求标题： " + title + "     </p>"
                + "<p>     需求描述： " + demand + "    </p>"
                + "</html>";
    }
}